package com.myproject.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Description: //TODO  简单的HTTP服务器， 其实就是接受HTTP请求，并解析请求，
 * @Author: sunfch
 * @Date: 2019/1/3 16:35
 * @Param:
 * @Return:
 */
public class ServerTest2 {


    public static void main(String[] args) throws Exception {



        ServerSocketChannel ss = ServerSocketChannel.open();  //服务端开启监听：接受客户端
        ss.bind(new InetSocketAddress(9960));
        ss.configureBlocking(false); //重点  OS  NONBLOCKING!!!  //只让接受客户端  不阻塞

        while (true){

            //接受客户端的连接
            Thread.sleep(1000);
            SocketChannel client = ss.accept(); //不会阻塞？  -1 NULL
            if (client!=null){
                client.configureBlocking(false);
                ClientHandler clientHandler = new ClientHandler(client);
                clientHandler.start();
            }

        }

    }

    public static class ClientHandler extends Thread{

        private SocketChannel socket;

        public ClientHandler(SocketChannel socket){
            this.socket = socket;
        }

        @Override
        public void run() {

            try {
                ByteBuffer buffer = ByteBuffer.allocateDirect(2048);  //可以在堆里   堆外
                while (true){
                    Thread.sleep(3000);
                    int num = socket.read(buffer);
                    System.out.println("num:"+num);
                    if (num>0){
                        //System.out.println(buffer);
                    }
                }

            } catch (Exception e){
                e.printStackTrace();
            }



        }
    }
}